package com.sentiment.report;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sentiment.config.Config;
import com.sentiment.config.ConfigDb;
import com.sentiment.contentextractor.News;
import com.sentiment.crawler.BaiduNewsCrawler;
import com.sentiment.crawler.DailyNewsCrawler;
import com.sentiment.database.bean.CrawlInfo;
import com.sentiment.database.bean.CrawlNews;
import com.sentiment.database.bean.DailyReport;
import com.sentiment.database.codec.DailyReportCodec;
import com.sentiment.database.dbUtil.DbCodecDriver;
import com.sentiment.sinalgo.Sinalgoer;
import com.sentiment.tools.Format;
import com.sentiment.tools.Generator;
import com.sentiment.tools.Transaction;

public class DailyReportUtils {
	private static final Logger LOG = LoggerFactory.getLogger(DailyReportUtils.class);
	private DbCodecDriver<DailyReport> driver = new DbCodecDriver<DailyReport>();
	/**
	 * 根据爬取新闻（CrawlNews）对象创建一篇每日舆情
	 * @param n
	 */
	private void createDailyReport(CrawlNews n) {
		
		// 创建每日舆情对象
		DailyReport dr = new DailyReport();
		//只取年/月/日
		dr.setDate(Format.date2String(n.getDate(),3));
		dr.setTitle(n.getTitle());
		dr.setText(n.getText());
		dr.setKeywords(n.getKeywords());
		//将DailyNewsCrawler爬取的第一篇新闻作为list中第一个id
		List<ObjectId> list = new ArrayList<ObjectId>();
		list.add(n.get_id());
		dr.setCrawlNews_id(list);
		dr.setStatus(false);
		
		BaiduNewsCrawler bnc = new BaiduNewsCrawler(Config.crawlerDataPath);
		bnc.getSearch(n.getTitle(), 1);
		
		Map<String, Double> mediaRatio = DataStatistics.mediaRatio(bnc.getNewsList());
		dr.setMediaRatio(mediaRatio);
		Map<String, Date> releaseTimeRatio = DataStatistics.releaseTimeRatio(bnc.getNewsList());
		dr.setReleaseTimeRatio(releaseTimeRatio);
		dr.setSentiment(Generator.genenrateDouble(0, 1));
		
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		driver.insert(dr);
		driver.closeConnection();
	}

	/**
	 * 将新闻文章中权重第一的关键词放到新浪微博搜索引擎中搜索前50条评论
	 * 
	 * @param n
	 * @deprecated
	 */
	private void createDailyReport(News n) {

		// AlgoHttp algoHttp = new AlgoHttp();
		List<String> src = Transaction.string2List(n.getContent());
		// List<Keywords> keywords = algoHttp.keywords(src);
		// String keyword = keywords.get(0).getWord();
		String keyword = Generator.generateKeyword();
		Sinalgoer sinalgoer = new Sinalgoer();
		List<CrawlInfo> infos = null;
		// if(keyword != null)
		// infos = sinalgoer.startSinaKeyword(keyword);
		if (keyword != null)
			infos = sinalgoer.startSinaKeyword(keyword);
		if (infos == null) {
			LOG.info("在新浪微博查询关键词 " + keyword + " 没有数据");
		} else {
//			for (CrawlInfo info : infos) {
//				ObjectId id = driver.insertGetId(info.toDocument());
//				weiboIds.add(id.toString());
//			}
//			dbu.closeConnection();

			// Map<String, Double> mediaRatio =
			// DataStatistics.mediaRatioParser(infos);
			// Map<String, Date> releaseTimeRatio =
			// DataStatistics.releaseTimeRatioParser(infos);
			// Map<String, Integer> commentRatio =
			// DataStatistics.commentStatistics(infos);
			// StatisticsInfo info = new StatisticsInfo(mediaRatio,
			// releaseTimeRatio, commentRatio);

			// dbu.openConnection(StatisticsInfo.dbName,
			// StatisticsInfo.collection);
			// statisticsInfo_id = dbu.insertGetId(info.toDocument());
			// dbu.closeConnection();
		}

		// 创建每日舆情对象
		DailyReport dr = new DailyReport();
		List<String> keywords = new ArrayList<String>();
		if (!Config.useNlp) {
			for (int i = 0; i < 3; i++) {
				keywords.add(Generator.generateKeyword());
			}
		}
		dr.setDate(Format.date2String(new Date(), 3));
		dr.setTitle(n.getTitle());
		dr.setText(src);
		dr.setStatus(false);

//		dbu.openConnection(DailyReport.dbName, DailyReport.collection);
//		dbu.insert(dr.toDocument());
//		dbu.closeConnection();
	}

	public void createTodayReport() {
		DailyNewsCrawler dnc = new DailyNewsCrawler(Config.crawlerDataPath);
		dnc.getSearch();
		List<CrawlNews> list = dnc.getNewslist();
		for (CrawlNews n : list) {
			createDailyReport(n);
		}
	}

	/**
	 * 根据Date对象找到所有当日生成的报告
	 * 
	 * @param date
	 * @return
	 */
	public List<DailyReport> findDailyReport(Date date) {
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		DailyReport dailyReport = new DailyReport();
		dailyReport.setDate(Format.date2String(date, 3));
		List<DailyReport> result = driver.queryMany(dailyReport);
		driver.closeConnection();
		return result;
	}
	/**
	 * 根据传入的id更新一个DailyReport的发布状态信息
	 * 修改已发布为未发布，未发布为已发布，并返回
	 * @param id
	 * @return
	 */
	public boolean updateStatus(ObjectId id){
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		DailyReport target = new DailyReport(id);
		DailyReport report = driver.query(target);
		//需要创建一个update的文档，对应$set的值为更新的文档
		DailyReport update = new DailyReport();
		report.setStatus(!report.getStatus());
		update.setUpdate("$set", report);
		driver.update(target, update);
		driver.closeConnection();
		return report.getStatus();
	}
	
	public DailyReport findDailyReport(ObjectId id) {
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		DailyReport result = driver.query(new DailyReport(id));
		driver.closeConnection();
		return result;

	}
	
	public void removeDailyReport(ObjectId id){
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		driver.remove(new DailyReport(id));
		driver.closeConnection();
	}
	/**
	 * 获取已发布或未发布的舆情报告
	 * 
	 * @param date
	 *            报告时间
	 * @param published
	 *            已发布为true
	 * @return
	 */
	public List<DailyReport> findDailyReport(Date date, boolean published) {
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		DailyReport dailyReport = new DailyReport();
		dailyReport.setDate(Format.date2String(date, 3));
		dailyReport.setStatus(published);
		List<DailyReport> result = driver.queryMany(dailyReport);
		driver.closeConnection();
		return result;

	}

	/**
	 * 根据传入的页码和每页显示的数量返回每日舆情报告的列表
	 * 
	 * @param pagenum
	 *            页码
	 * @param pageview
	 *            每页显示数
	 * @return
	 */
	public List<DailyReport> findDailyReport(int pagenum, int pageview) {
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		List<DailyReport> list = driver.getPage(pagenum, pageview);
		driver.closeConnection();
		return list;
	}
	/**
	 * 返回所有已发布或未发布的每日舆情报告
	 * @param published
	 * @return
	 */
	public List<DailyReport> findDailyReport(boolean published){
		driver.openConnection(ConfigDb.sentimentDb, DailyReport.class, DailyReportCodec.class);
		List<DailyReport> list = driver.queryMany(new DailyReport(published));
		driver.closeConnection();
		return list;
	}
}
